window.onload = function () {
  initMap();
  loadData();
  // toggleFullScreen();
};

// 初始化数据
let map;
const mapZoom = 14;
let coordinates = null;
let shipMarkers = []; // 存储船舶标记
let shipsData = []; // 存储所有船舶数据
let alertMessage = null;

// 初始化地图
function initMap() {
  map = new BMap.Map('map');
  map.centerAndZoom(new BMap.Point(108.093462, 22.8773242), mapZoom);
  map.setCurrentCity('西江');
  map.enableScrollWheelZoom(true);
  map.enableContinuousZoom(true);
  // 设置地图类型为卫星图
  map.setMapType(BMAP_SATELLITE_MAP);
}

// 添加船舶标记
function addShipMarkers() {
  // 按照时间排序船舶数据
  shipsData.sort((a, b) => new Date(a.GPS_TIME) - new Date(b.GPS_TIME));

  const points = [];
  const iconNames = ['sship1.png', 'sship2.png', 'sship3.png', 'sship4.png', 'sship5.png'];

  shipsData.forEach(ship => {
    const point = new BMap.Point(ship.FIX_X, ship.FIX_Y);
    points.push(point);

    // 随机选择一个图标
    const randomIndex = Math.floor(Math.random() * iconNames.length);
    const iconName = iconNames[randomIndex];
    const shipIcon = new BMap.Icon(`/files/${iconName}`, new BMap.Size(32, 32));

    const shipMarker = new BMap.Marker(point, { icon: shipIcon });
    map.addOverlay(shipMarker);
    shipMarkers.push(shipMarker);

    // 为标记添加点击事件
    shipMarker.addEventListener('click', () => {
      showAlert(`经度: ${ship.FIX_X}<br>纬度: ${ship.FIX_Y}<br>时间: ${ship.GPS_TIME}`);
    });
  });
}

// 加载数据
function loadData() {
  const filePath = '/files/北斗定位数据for桂林理工.xlsx';
  fetch(filePath)
      .then(response => {
        if (!response.ok) {
          throw new Error('网络响应不正常');
        }
        return response.arrayBuffer();
      })
      .then(data => {
        try {
          const workbook = XLSX.read(data, { type: 'array' });
          const worksheet = workbook.Sheets[workbook.SheetNames[0]];

          if (!worksheet) {
            throw new Error('未找到工作表');
          }

          const jsonData = XLSX.utils.sheet_to_json(worksheet);
          console.log('加载的数据:', jsonData);

          // 清空当前的船舶数据
          shipsData = [];

          // 遍历 JSON 数据并添加到 shipsData
          jsonData.forEach(item => {
            shipsData.push({
              FIX_X: item['FIX_X'],
              FIX_Y: item['FIX_Y'],
              GPS_TIME: formatExcelDate(item['GPS_TIME'])
            });
          });

          // 添加船舶标记到地图
          addShipMarkers();
        } catch (error) {
          console.error('解析 Excel 文件时出错:', error);
        }
      })
      .catch(error => console.error('加载文件时出错:', error));
}

// 转换 Excel 日期格式
function formatExcelDate(excelDate) {
  const date = new Date((excelDate - 25569) * 86400 * 1000);
  return date.toLocaleString();
}

// 显示提示信息
function showAlert(message) {
  alertMessage = message;
  const alertElement = document.getElementById('alert-message');
  alertElement.innerHTML = message;
  alertElement.style.display = 'block';
}

// 切换全屏模式
function toggleFullScreen() {
  const mapElement = document.getElementById('map');
  if (mapElement.requestFullscreen) {
    mapElement.requestFullscreen();
  } else if (mapElement.mozRequestFullScreen) {
    mapElement.mozRequestFullScreen();
  } else if (mapElement.webkitRequestFullscreen) {
    mapElement.webkitRequestFullscreen();
  } else if (mapElement.msRequestFullscreen) {
    mapElement.msRequestFullscreen();
  }
}

// 页面加载完成后初始化
window.onload = function () {
  initMap();
  loadData();
  // toggleFullScreen();
};